package cn.zc.student.service.service.impl;

import cn.tools.core.exception.BizException;
import cn.tools.dozer.config.DozerUtils;
import cn.zc.student.entity.Dto.StudentExercisesRespondenceDto;
import cn.zc.student.entity.StudentExercisesRespondence;
import cn.zc.student.service.mapper.StudentExercisesRespondenceMapper;
import cn.zc.student.service.service.StudentExercisesRespondenceService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 学生练习题作答 服务实现类
 * </p>
 *
 * @author keno
 * @since 2022-02-23
 */
@Service
public class StudentExercisesRespondenceServiceImpl extends ServiceImpl<StudentExercisesRespondenceMapper, StudentExercisesRespondence> implements StudentExercisesRespondenceService {

    @Resource
    private StudentExercisesRespondenceMapper studentExercisesRespondenceMapper;

    @Resource
    private DozerUtils dozerUtils;

    /**
     * 保存作答记录，如果有作答记录则进行删除或修改处理
     * @param list
     * @return
     */
    @Override
    public boolean createStudentExercisesRespondence(List<StudentExercisesRespondence> list) {
        if(list == null || list.isEmpty()) {
            throw new BizException("插入练习题作答数据失败，传递参数list为空");
        }

        /**
         * 先查询检测是否存在数据
         */
        List<StudentExercisesRespondence> studentExercisesRespondences = studentExercisesRespondenceMapper.selectList(new QueryWrapper<StudentExercisesRespondence>().lambda()
                .eq(StudentExercisesRespondence::getMenuId, list.get(0).getMenuId())
                .eq(StudentExercisesRespondence::getStudentId, list.get(0).getStudentId())
        );

        //TODO 检查数据是否存在，存在则删除，本意是设计学生可以多次作答，可以查询每次作答记录，但老大否决，直接覆盖就行，这里记录一下，方便后续扩展时修改代码
        studentExercisesRespondenceMapper.deleteBatchIds(studentExercisesRespondences);

        return saveBatch(list);
    }

    /**
     * 查询出学生作答
     * @param menuId
     * @param studentId
     * @return
     */
    @Override
    public List<StudentExercisesRespondenceDto> findStudentExercisesRespondence(String menuId, String studentId) {
        List<StudentExercisesRespondence> studentExercisesRespondences = studentExercisesRespondenceMapper.selectList(new QueryWrapper<StudentExercisesRespondence>().lambda()
                .eq(StudentExercisesRespondence::getMenuId, menuId)
                .eq(StudentExercisesRespondence::getStudentId, studentId));

        return dozerUtils.mapList(studentExercisesRespondences, StudentExercisesRespondenceDto.class);

    }
}
